<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="close">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="form.title" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="子标题" prop="subTitle">
          <el-input v-model.trim="form.subTitle" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="预览图">
          <el-upload
            :file-list="fileList"
            action="imageUrl"
            list-type="picture-card"
            :before-upload="imageUrlBeforeUpload"
            :on-remove="removeFile"
            name="file"
            :http-request="uploadImage"
            multiple
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- <el-input v-model="form.imageUrl" maxlength="20"></el-input> -->
        </el-form-item>
        <el-upload
          class="avatar-uploader"
          action="serverUrl"
          name="img"
          :show-file-list="false"
          :http-request="uploadImageVab"
        ></el-upload>
        <el-form-item label="内容" prop="context" class="vab-quill-content">
          <vab-quill
            ref="myQuillEditor"
            v-model="form.context"
            :min-height="400"
            :options="options"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          ></vab-quill>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="handleSee()">预览效果</el-button>
        <el-button type="primary" @click="handleSave()">保 存</el-button>
      </div>
    </el-dialog>
    <!-- //预览效果 -->
    <el-dialog
      title="预览效果"
      :visible.sync="dialogTableVisible"
      append-to-body
    >
      <div style="min-height: 60vh">
        <h1 class="news-title">{{ form.title }}</h1>
        <div class="news-content" v-html="form.context"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import vabQuill from '@/plugins/vabQuill'
  import { upload } from '@/api/upload'
  import { addNews, getNewDetail, editNews } from '@/api/new'
  import { uuid, parseTime } from '@/utils/index'
  import store from '@/store'
  import _net from '../../../config/net.config'

  // 工具栏配置
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
    [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
    [{ direction: 'rtl' }], // text direction

    [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
    ['image'],
    ['clean'], // remove formatting button
  ]

  export default {
    name: 'EditorForm',
    components: { vabQuill },
    data() {
      return {
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示

        options: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          modules: {
            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                image: function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                },
              },
            },
          },
          placeholder: '内容...',
          readOnly: false,
        },
        borderColor: '#dcdfe6',
        dialogTableVisible: false,
        fileList: [],
        form: {
          browseCount: 0, //浏览量
          context: '',
          imageUrl: '',
          infoId: '', //随机id
          publishDate: '',
          publisherId: '', //上传者id
          publisherName: '',
          subTitle: '',
          title: '',
        },
        rules: {
          title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
          subTitle: [
            { required: true, trigger: 'blur', message: '请输入子标题' },
          ],
          context: [{ required: true, trigger: 'blur', message: '请输入正文' }],
        },
        title: '',
        dialogFormVisible: false,
        show: false,
      }
    },
    created() {
      // this.form.roleId=this.StatusOptions[3].key
    },

    methods: {
      async uploadImageVab(param) {
        const formData = new FormData()
        // formData.fileType = 1
        formData.append('fileType', 1)
        formData.append('file', param.file)
        this.quillUpdateImg = true
        const { data } = await upload(formData)
        // let base = 'https://app.aixinfang.vip'
        // let base = 'https://note.zjut.club'
        let base = _net.baseURL
        let _imageUrl = base + '/file/download?fileId=' + data.body.fileId

        if (data.status == 0) {
          console.log(this.$refs.myQuillEditor)
          let quill = this.$refs.myQuillEditor.Quill
          console.log(quill)
          // 如果上传成功
          // 获取光标所在位置
          let length = quill.getSelection().index
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, 'image', _imageUrl)
          // 调整光标到最后
          quill.setSelection(length + 1)
          console.log(quill)
          // loading动画消失
          this.quillUpdateImg = false
        } else {
          this.quillUpdateImg = false

          this.$message.error('图片插入失败')
        }
      },
      resize() {
        this.form = {
          browseCount: 0, //浏览量
          context: '',
          imageUrl: '',
          infoId: '', //随机id
          publishDate: '',
          publisherId: '', //上传者id
          publisherName: '',
          subTitle: '',
          title: '',
        }
        this.fileList = []
      },
      showEdit(row) {
        this.resize()
        if (!row) {
          this.title = '新建资讯'
          this.show = false
        } else {
          this.title = '修改资讯'
          this.show = true
          // console.log(row)
          // let base = 'https://note.zjut.club'
          let base = _net.baseURL
          const element = base + '/file/download?fileId=' + row.imageUrl
          this.fileList.push({
            url: element,
            id: row.imageUrl,
          })
          this.fetchNewData(row.infoId)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.resize()
        this.dialogFormVisible = false
      },
      imageUrlBeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize
      },
      removeFile(file, fileList) {
        console.log(file)
        console.log(fileList)
        let _temp = this.fileList.filter(function (item) {
          return item.id != file.id
        })
        this.fileList = _temp
      },
      async uploadImage(param) {
        console.log(param)
        const formData = new FormData()
        formData.append('fileType', 1)
        formData.append('file', param.file)
        console.log(formData)
        const { data } = await upload(formData)
        if (data.status == 0) {
          // let base = 'https://note.zjut.club'
          let base = _net.baseURL
          const element = base + '/file/download?fileId=' + data.body.fileId
          this.fileList.push({ url: element, id: data.body.fileId })
        } else {
          this.$baseMessage(data.message, 'error')
        }
        console.log(this.fileList)
      },
      handleSee() {
        this.$refs['form'].validate((valid) => {
          this.$refs.form.validateField('context', (errorMsg) => {})
          if (valid) {
            this.dialogTableVisible = true
          } else {
            return false
          }
        })
      },
      //获取单项详情
      async fetchNewData(infoId) {
        const { data } = await getNewDetail(infoId)
        const { body } = data
        this.form = Object.assign({}, body)
      },

      handleSave() {
        this.$refs['form'].validate(async (valid) => {
          this.$refs.form.validateField('context', (errorMsg) => {
            console.log(this.form)
          })
          if (valid) {
            if (this.fileList.length == 0) {
              this.$baseMessage('上传的预览图片不能为空', 'error')
              return
            }
            let formatData = this.form
            formatData.imageUrl = this.fileList[0].id
            formatData.publisherId = store.getters['user/userId']
            formatData.publisherName = store.getters['user/username']
            let time = new Date()
            formatData.publishDate = parseTime(time)
            if (this.title == '新建资讯') {
              formatData.infoId = uuid(32)
              formatData.browseCount = 0
              const { data } = await addNews(this.form)
              if (data.status == 0) {
                this.$baseMessage('新建资讯成功！', 'success')
                this.$emit('fetch-data')
                this.close()
              } else {
                this.$baseMessage(data.message, 'error')
              }
            } else {
              const { data } = await editNews(this.form)
              if (data.status == 0) {
                this.$baseMessage('修改资讯成功！', 'success')
                this.$emit('fetch-data')
                this.close()
              } else {
                this.$baseMessage(data.message, 'error')
              }
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .avatar-uploader {
    display: none;
  }
</style>
